package game;

import java.io.*;
import java.net.*;

public class Table implements Runnable
{
	private int serverPort = 4444;
	private int bankroll = 0;
	private ServerSocket serverSocket = null;
	private boolean isStopped = false;
	private Thread runningThread = null;
	private int playerCount = 0;
	
	public Table(int port, String[] argv) throws IOException
	{
		this.serverPort = port;
		try 
		{
			this.playerCount = Integer.parseInt(argv[0]);
			this.bankroll = Integer.parseInt(argv[1]);
		}
		catch (NumberFormatException nfe)
		{
			nfe.printStackTrace();
		}
	}
	
	@Override
	public void run()
	{
		synchronized(this)
		{
			this.runningThread = Thread.currentThread();
		}
		openServerSocket();
		
		while(!isStopped())
		{
			Socket clientSocket = null;
			if(playerCount<6)
			{
				try
				{
					clientSocket = this.serverSocket.accept();
				}
				catch(IOException ioe)
				{
					if(isStopped())
					{
						System.out.println("Server Stopped.");
						return;
					}
					throw new RuntimeException("Error accepting client connection", ioe);
				}
				
				new Thread(new WorkerRunnable(clientSocket)).start();
			}
			/*else            IN PROGRESS
			{
				clientSocket = this.serverSocket.wait();
			}*/
		}
		System.out.println("Server Stopped.");
	}
	
	private synchronized boolean isStopped()
	{
		return this.isStopped;
	}
	
	public synchronized void stop()
	{
		this.isStopped = true;
		try
		{
			this.serverSocket.close();
		}
		catch(IOException ioe)
		{
			throw new RuntimeException("Error closing server", ioe);
		}
	}
	
	private void openServerSocket()
	{
		try
		{
			this.serverSocket = new ServerSocket(this.serverPort);
		}
		catch(IOException ioe)
		{
			throw new RuntimeException("Cannot open port " + this.serverPort, ioe);
		}
	}
	
	public int getBankroll() 
	{
		return this.bankroll;
	}
	
	public int getPlayerCount() 
	{
		return this.playerCount;
	}
	
	
	public static void main(String[] argv)
	{
		try 
		{
			Table server = new Table(4444, argv);
			new Thread(server).start();
		} 
		catch (IOException ioe) 
		{
			ioe.printStackTrace();
		}
	
	}
	
	
	
}